﻿//-----------------------------------------------------------------------
// <copyright file="CounterManager.cs" company="Paul V. Borza">
// http://fastget.codeplex.com/license
// </copyright>
//-----------------------------------------------------------------------

namespace FastGet
{
    using System.Configuration;
    using System.Diagnostics;

    /// <remarks>
    /// To create a *.perfmoncfg file perfmon.exe needs to be first run with the /sys parameter.
    /// Then File > Save settings as... will do the rest.
    /// </remarks>
    internal static class CounterManager
    {
        private static string performanceCounterCategoryName = ConfigurationManager.AppSettings["PerformanceCounterCategoryName"];
        private static string performanceCounterCategoryHelp = ConfigurationManager.AppSettings["PerformanceCounterCategoryHelp"];

        private static string httpRequestsCounterName = ConfigurationManager.AppSettings["HttpRequestsCounterName"];
        private static string httpRequestsCounterHelp = ConfigurationManager.AppSettings["HttpRequestsCounterHelp"];

        private static string httpResponsesCounterName = ConfigurationManager.AppSettings["HttpResponsesCounterName"];
        private static string httpResponsesCounterHelp = ConfigurationManager.AppSettings["HttpResponsesCounterHelp"];

        public static PerformanceCounter HttpRequests { get; private set; }

        public static PerformanceCounter HttpResponses { get; private set; }

        public static void Setup()
        {
            if (!PerformanceCounterCategory.Exists(performanceCounterCategoryName))
            {
                var collection = new CounterCreationDataCollection()
                {
                    new CounterCreationData(httpRequestsCounterName, httpRequestsCounterHelp, PerformanceCounterType.SampleCounter),
                    new CounterCreationData(httpResponsesCounterName, httpResponsesCounterHelp, PerformanceCounterType.SampleCounter)
                };

                PerformanceCounterCategory.Create(performanceCounterCategoryName, performanceCounterCategoryHelp, PerformanceCounterCategoryType.SingleInstance, collection);
            }

            HttpRequests = new PerformanceCounter(performanceCounterCategoryName, httpRequestsCounterName, false)
            {
                RawValue = 0
            };

            HttpResponses = new PerformanceCounter(performanceCounterCategoryName, httpResponsesCounterName, false)
            {
                RawValue = 0
            };
        }
    }
}
